<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="加载失败，请点击重试"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.id" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'searchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      page: 1,
      perPage: 20
    }
  },
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      try {
        // 获取数据
        const { data } = await getSearchResult({
          page: this.page,
          per_page: this.perPage,
          q: this.searchText
        })
        // 添加到数组
        const { results } = data.data
        this.list.push(...results)
        // 将加载中的loading关闭
        this.loading = false
        // 判断是否有数据
        if (results.length) {
          // 有就加一页
          this.page++
        } else {
          // 没有就结束
          this.finished = true
        }
      } catch (err) {
        // 加载失败显示失败信息
        this.error = true
        // loading也要关闭
        this.loading = false
      }
    }
  }
}
</script>
<style scoped lang="less"></style>
